<template>
  <div class="report-container">
    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" :inline="true">
        <el-form-item label="统计维度" prop="dimension">
          <el-select v-model="searchForm.dimension" placeholder="请选择统计维度" style="width: 180px">
            <el-option label="按日统计" value="DAY" />
            <el-option label="按周统计" value="WEEK" />
            <el-option label="按月统计" value="MONTH" />
            <el-option label="按年统计" value="YEAR" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="产品类别" prop="productCategory">
          <el-select v-model="searchForm.productCategory" placeholder="请选择产品类别" clearable style="width: 180px">
            <el-option label="电子产品" value="ELECTRONICS" />
            <el-option label="机械产品" value="MACHINERY" />
            <el-option label="化工产品" value="CHEMICAL" />
          </el-select>
        </el-form-item>
        <el-form-item label="车间" prop="workshop">
          <el-select v-model="searchForm.workshop" placeholder="请选择车间" clearable style="width: 180px">
            <el-option label="装配车间" value="ASSEMBLY" />
            <el-option label="机加车间" value="MACHINING" />
            <el-option label="包装车间" value="PACKAGING" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" :icon="Download" @click="handleExport">导出报表</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value production-count">{{ statsData.totalProduction }}</div>
              <div class="stat-label">总产量</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value pass-rate">{{ statsData.passRate }}%</div>
              <div class="stat-label">合格率</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value efficiency">{{ statsData.efficiency }}%</div>
              <div class="stat-label">生产效率</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value on-time-rate">{{ statsData.onTimeRate }}%</div>
              <div class="stat-label">按时完成率</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>生产趋势图</span>
              </div>
            </template>
            <div ref="productionTrendChart" class="chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>产品类别分布</span>
              </div>
            </template>
            <div ref="productCategoryChart" class="chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>车间产量对比</span>
              </div>
            </template>
            <div ref="workshopCompareChart" class="chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>质量指标趋势</span>
              </div>
            </template>
            <div ref="qualityTrendChart" class="chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 详细数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>生产明细数据</span>
        </div>
      </template>
      
      <el-table :data="tableData" style="width: 100%" v-loading="loading" border>
        <el-table-column prop="date" label="日期" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="workshop" label="车间" />
        <el-table-column prop="plannedQuantity" label="计划产量" align="right" />
        <el-table-column prop="actualQuantity" label="实际产量" align="right" />
        <el-table-column prop="passQuantity" label="合格数量" align="right" />
        <el-table-column prop="completionRate" label="完成率" align="right">
          <template #default="scope">
            <span :class="getCompletionRateClass(scope.row.completionRate)">{{ scope.row.completionRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="passRate" label="合格率" align="right">
          <template #default="scope">
            <span :class="getPassRateClass(scope.row.passRate)">{{ scope.row.passRate }}%</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="productionReport">
import { ref, reactive, onMounted, nextTick } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { Download } from "@element-plus/icons-vue";
import * as echarts from "echarts";

const loading = ref(false);
const tableData = ref([]);
const searchFormRef = ref<FormInstance>();

// 图表引用
const productionTrendChart = ref();
const productCategoryChart = ref();
const workshopCompareChart = ref();
const qualityTrendChart = ref();

// 查询表单
const searchForm = reactive({
  dimension: "DAY",
  dateRange: [],
  productCategory: "",
  workshop: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 统计数据
const statsData = reactive({
  totalProduction: 12580,
  passRate: 96.8,
  efficiency: 88.5,
  onTimeRate: 92.3
});

// 获取完成率样式
const getCompletionRateClass = (rate: number) => {
  if (rate >= 100) return "rate-excellent";
  if (rate >= 90) return "rate-good";
  if (rate >= 80) return "rate-normal";
  return "rate-poor";
};

// 获取合格率样式
const getPassRateClass = (rate: number) => {
  if (rate >= 95) return "rate-excellent";
  if (rate >= 90) return "rate-good";
  if (rate >= 85) return "rate-normal";
  return "rate-poor";
};

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    // 生产趋势图
    if (productionTrendChart.value) {
      const trendChart = echarts.init(productionTrendChart.value);
      const trendOption = {
        tooltip: { trigger: 'axis' },
        legend: { data: ['计划产量', '实际产量'] },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: { type: 'value' },
        series: [
          {
            name: '计划产量',
            type: 'line',
            data: [1200, 1350, 1100, 1400, 1250, 1300]
          },
          {
            name: '实际产量',
            type: 'line',
            data: [1150, 1320, 1080, 1380, 1200, 1280]
          }
        ]
      };
      trendChart.setOption(trendOption);
    }

    // 产品类别分布图
    if (productCategoryChart.value) {
      const categoryChart = echarts.init(productCategoryChart.value);
      const categoryOption = {
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left' },
        series: [
          {
            name: '产品类别',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 1048, name: '电子产品' },
              { value: 735, name: '机械产品' },
              { value: 580, name: '化工产品' }
            ]
          }
        ]
      };
      categoryChart.setOption(categoryOption);
    }

    // 车间产量对比图
    if (workshopCompareChart.value) {
      const workshopChart = echarts.init(workshopCompareChart.value);
      const workshopOption = {
        tooltip: { trigger: 'axis' },
        legend: { data: ['本月', '上月'] },
        xAxis: {
          type: 'category',
          data: ['装配车间', '机加车间', '包装车间']
        },
        yAxis: { type: 'value' },
        series: [
          {
            name: '本月',
            type: 'bar',
            data: [820, 932, 701]
          },
          {
            name: '上月',
            type: 'bar',
            data: [780, 890, 650]
          }
        ]
      };
      workshopChart.setOption(workshopOption);
    }

    // 质量指标趋势图
    if (qualityTrendChart.value) {
      const qualityChart = echarts.init(qualityTrendChart.value);
      const qualityOption = {
        tooltip: { trigger: 'axis' },
        legend: { data: ['合格率', '返工率'] },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: { type: 'value', max: 100 },
        series: [
          {
            name: '合格率',
            type: 'line',
            data: [95.2, 96.1, 94.8, 96.5, 97.2, 96.8]
          },
          {
            name: '返工率',
            type: 'line',
            data: [3.2, 2.8, 3.5, 2.1, 1.8, 2.3]
          }
        ]
      };
      qualityChart.setOption(qualityOption);
    }
  });
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        date: "2024-01-15",
        productName: "智能手机X1",
        workshop: "装配车间",
        plannedQuantity: 100,
        actualQuantity: 95,
        passQuantity: 92,
        completionRate: 95.0,
        passRate: 96.8
      },
      {
        date: "2024-01-15",
        productName: "工业机器人A1",
        workshop: "机加车间",
        plannedQuantity: 10,
        actualQuantity: 12,
        passQuantity: 11,
        completionRate: 120.0,
        passRate: 91.7
      }
    ];
    
    tableData.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    console.error("获取生产报表数据失败:", error);
    ElMessage.error("获取生产报表数据失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
  initCharts();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
  initCharts();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 导出报表
const handleExport = () => {
  ElMessage.info("导出生产报表功能开发中");
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
  initCharts();
});
</script>

<style scoped>
.report-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 20px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.production-count {
  color: #409eff;
}

.pass-rate {
  color: #67c23a;
}

.efficiency {
  color: #e6a23c;
}

.on-time-rate {
  color: #f56c6c;
}

.charts-container {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.rate-excellent {
  color: #67c23a;
  font-weight: bold;
}

.rate-good {
  color: #409eff;
  font-weight: bold;
}

.rate-normal {
  color: #e6a23c;
  font-weight: bold;
}

.rate-poor {
  color: #f56c6c;
  font-weight: bold;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>